import pickle


class Student:
    def __init__(self, name, student_id, age, score):
        self.name = name
        self.student_id = student_id
        self.age = age
        self.score = score

    def __str__(self):
        return f"姓名：{self.name}, 学号：{self.student_id}, 年龄：{self.age}, 成绩：{self.score}"


class StudentManager:
    def __init__(self, filename='students.dat'):
        self.filename = filename
        self.students = self.load_students()

    def load_students(self):
        try:
            with open(self.filename, 'rb') as file:
                return pickle.load(file)
        except (FileNotFoundError, EOFError):
            return []

    def save_students(self):
        with open(self.filename, 'wb') as file:
            pickle.dump(self.students, file)

    def add_student(self, name, student_id, age, score):
        try:
            student_id = int(student_id)  # 确保学号是数字
            self.students.append(Student(name, student_id, age, score))
            self.save_students()
            print("学生信息添加成功！")
        except ValueError:
            print("错误：学号必须为数字！")

    def display_all_students(self):
        if not self.students:
            print("没有学生信息。")
        else:
            for student in self.students:
                print(student)

    def find_student_by_id(self, student_id):
        try:
            student_id = int(student_id)
            for student in self.students:
                if student.student_id == student_id:
                    print(student)
                    return
            print("未找到学号为", student_id, "的学生。")
        except ValueError:
            print("错误：学号必须为数字！")

    def sort_students_by_score(self):
        self.students.sort(key=lambda x: float(x.score), reverse=True)
        print("按成绩从高到低排序：")
        self.display_all_students()


def main():
    manager = StudentManager()
    while True:
        print("\n1. 添加学生信息")
        print("2. 显示所有学生信息")
        print("3. 根据学号查找学生信息")
        print("4. 根据成绩排序并显示学生信息")
        print("5. 退出")
        choice = input("请选择一个操作：")

        if choice == '1':
            name = input("请输入学生姓名：")
            student_id = input("请输入学生学号：")
            age = input("请输入学生年龄：")
            score = input("请输入学生成绩：")
            manager.add_student(name, student_id, age, score)
        elif choice == '2':
            manager.display_all_students()
        elif choice == '3':
            student_id = input("请输入要查找的学生学号：")
            manager.find_student_by_id(student_id)
        elif choice == '4':
            manager.sort_students_by_score()
        elif choice == '5':
            print("退出系统。")
            break
        else:
            print("无效的输入，请重新选择。")


if __name__ == "__main__":
    main()
